package com.snap.vseries.fragment;

import android.content.Intent;
import android.graphics.Outline;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.snap.vseries.R;
import com.snap.vseries.adapter.HistoryAdapter;
import com.snap.vseries.base.BaseFragment;
import com.snap.vseries.base.BaseViewHolder;
import com.snap.vseries.bean.ExpEntity;
import com.snap.vseries.manager.FileManager;
import com.snap.vseries.model.DBManager;
import com.snap.vseries.ui.ExpResultActivity;
import com.snap.vseries.ui.HisSearchActivity;
import com.snap.vseries.ui.widget.BottomDivider;
import com.snap.vseries.ui.widget.DialogView;
import com.snap.vseries.utils.ToastUtils;

import org.litepal.crud.callback.FindMultiCallback;
import org.litepal.crud.callback.UpdateOrDeleteCallback;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import me.jessyan.autosize.utils.AutoSizeUtils;

public class HistoryFragment extends BaseFragment {
    @BindView(R.id.search_ll)
    ViewGroup searchLl;
    @BindView(R.id.container)
    LinearLayout container;
    @BindView(R.id.no_his_ll)
    LinearLayout noHisLl;
    @BindView(R.id.container_nv)
    NestedScrollView containerNv;


    @Override
    protected int layoutResId() {
        return R.layout.fragment_history;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
        initView();
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
        initView();
    }

    private void initData() {
        DBManager.get().getExp(new FindMultiCallback<ExpEntity>() {
            @Override
            public void onFinish(List<ExpEntity> list) {
                if (list == null || list.size() == 0) {
                    noHisLl.setVisibility(View.VISIBLE);
                    containerNv.setVisibility(View.GONE);
                    return;
                }
                noHisLl.setVisibility(View.GONE);
                containerNv.setVisibility(View.VISIBLE);
                initRecyclerView(list);
            }
        });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            initData();
        }
    }

    private void initView() {
        //=======================测试数据=============================
        //一周内
        //一月内
        //半年内
        //年份倒序

        searchLl.setOnClickListener(v -> {
            Intent intent = new Intent(getContext(), HisSearchActivity.class);
            startActivity(intent);
        });
    }

    private void initRecyclerView(List<ExpEntity> list) {
        container.removeAllViews();
        long minTime = list.get(list.size() - 1).getStartTime();
        long currentTime = System.currentTimeMillis();
        long weekTime = currentTime - 7 * 24 * 60 * 60 * 1000L;
        long moonTime = currentTime - 30 * 24 * 60 * 60 * 1000L;
        long halfYearTime = currentTime - 365 / 2 * 24 * 60 * 60 * 1000L;
        List<ExpEntity> weekList = new ArrayList<>();
        List<ExpEntity> moonList = new ArrayList<>();
        List<ExpEntity> halfYearList = new ArrayList<>();
        LinkedHashMap<Integer, List<ExpEntity>> map = new LinkedHashMap<>();
        int minYear = getYear(minTime);
        int currentYear = getCurrentYear();
        for (ExpEntity history : list) {
            long time = history.getStartTime();
            if (time > weekTime) {
                weekList.add(history);
            } else if (time > moonTime) {
                moonList.add(history);
            } else if (time > halfYearTime) {
                halfYearList.add(history);
            } else {
                for (int i = currentYear; i >= minYear; i--) {
                    if (map.get(i) == null) {
                        map.put(i, new ArrayList<>());
                    }
                    if (getYear(time) == i) {
                        map.get(i).add(history);
                    }
                }
            }
        }
        if (weekList.size() > 0) {
            container.addView(newTextView(getString(R.string.the_past_week), 0 == container.getChildCount()));
            container.addView(newRecyclerView(weekList));
        }
        if (moonList.size() > 0) {
            container.addView(newTextView(getString(R.string.the_past_month), 0 == container.getChildCount()));
            container.addView(newRecyclerView(moonList));
        }
        if (halfYearList.size() > 0) {
            container.addView(newTextView(getString(R.string.the_past_year), 0 == container.getChildCount()));
            container.addView(newRecyclerView(halfYearList));
        }
        for (int key : map.keySet()) {
            List<ExpEntity> yearList = map.get(key);
            if (yearList != null && yearList.size() > 0) {
                container.addView(newTextView(String.valueOf(key), 0 == container.getChildCount()));
                container.addView(newRecyclerView(yearList));
            }
        }
    }

    private RecyclerView newRecyclerView(List<ExpEntity> list) {
        RecyclerView recyclerView = new RecyclerView(getContext());
        recyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        HistoryAdapter adapter = new HistoryAdapter(getActivity(), list);
        recyclerView.setAdapter(adapter);
        adapter.setOnLongClickLitener(new BaseViewHolder.onItemCommonLongClickListener() {
            @Override
            public void onItemLongClickListener(View view, int position) {
                delete(list.get(position).getName());
            }
        });
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(AutoSizeUtils.dp2px(getContext(), 24), AutoSizeUtils.dp2px(getContext(), 10), AutoSizeUtils.dp2px(getContext(), 24), 0);
        recyclerView.setPadding(0, AutoSizeUtils.dp2px(getContext(), 8), 0, AutoSizeUtils.dp2px(getContext(), 8));
        recyclerView.setLayoutParams(params);
        recyclerView.setBackground(ContextCompat.getDrawable(getContext(), R.drawable.bg_history));
        //
        recyclerView.addItemDecoration(new BottomDivider(AutoSizeUtils.dp2px(getContext(), 16)));
        recyclerView.setOutlineProvider(new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), 4);
            }
        });
        adapter.setOnItemClickLitener((view, position) -> {
            Intent expResult = new Intent(getContext(), ExpResultActivity.class);
            expResult.putExtra("fileName", list.get(position).getName());
            startActivity(expResult);
        });
        return recyclerView;
    }

    private void delete(String name) {
        final DialogView dialogView = new DialogView(getContext());
        dialogView.setTitle("删除实验");
        dialogView.setTextContent("删除后不可恢复，是否确认删除？");
        dialogView.setOnClickListener("仍然删除", new DialogView.OnSureListener() {
            @Override
            public void onSureClick(String content) {
                deleteExp(name);
            }
        }).show();
    }

    private void deleteExp(String name) {
        DBManager.get().deleteExp(new UpdateOrDeleteCallback() {
            @Override
            public void onFinish(int rowsAffected) {
                if (rowsAffected > 0) {
                    FileManager.getInstance().removeExpData(name);
                    ToastUtils.get().showText("删除实验成功");
                    initData();
                }
            }
        }, name);
    }

    private TextView newTextView(String content, boolean isFirstStage) {
        TextView textView = new TextView(getContext());
        textView.setText(content);
        textView.setTextSize(14);
        textView.setTextColor(0xff568BFF);
        textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        Drawable drawableLeft = ContextCompat.getDrawable(getContext(), R.drawable.ic_history);
        textView.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null);
        textView.setCompoundDrawablePadding(AutoSizeUtils.dp2px(getContext(), 10));
        textView.setPadding(36, 0, 24, 0);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, AutoSizeUtils.dp2px(getContext(), 32));
        if (!isFirstStage) {
            params.setMargins(0, AutoSizeUtils.dp2px(getContext(), 24), 0, AutoSizeUtils.dp2px(getContext(), 3));
        }
        textView.setLayoutParams(params);
        textView.setGravity(Gravity.CENTER_VERTICAL);
        return textView;
    }

    /**
     * 获取年
     *
     * @return
     */
    public int getCurrentYear() {
        Calendar cd = Calendar.getInstance();
        return cd.get(Calendar.YEAR);
    }

    /**
     * 获取年
     *
     * @return
     */
    public int getYear(long time) {
        Calendar c = Calendar.getInstance();
        c.setTime(new Date(time));
        return c.get(Calendar.YEAR);
    }
}
